package main

import (
	"context"
	"fmt"
	"io"
	"net"

	api "gitee.com/lcc_dr/rpc/api"
	"gitee.com/lcc_dr/rpc/grpc/middleware"
	"google.golang.org/grpc"
)

//HelloServiceServer 实现类
type Service struct {
	api.UnimplementedHelloServiceServer
}

func NewService() *Service {
	return &Service{}
}

//重写hello方法
func (s *Service) Hello(ctx context.Context, req *api.Request) (replay *api.Response, err error) {

	replay = &api.Response{Value: fmt.Sprintf("hello, %s", req.Value)}
	return replay, nil
}

func (s *Service) Channel(stream api.HelloService_ChannelServer) error {

	for {
		req, err := stream.Recv()

		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err

		}
		fmt.Println(req.Value)
		replay := &api.Response{Value: fmt.Sprintf("%s streaming", req.Value)}

		stream.Send(replay)

	}
}

// func (s *Service) mustEmbedUnimplementedHelloServiceServer() {}

func main() {
	opts := []grpc.ServerOption{
		// The following grpc.ServerOption adds an interceptor for all unary
		// RPCs. To configure an interceptor for streaming RPCs, see:
		// https://godoc.org/google.golang.org/grpc#StreamInterceptor
		grpc.UnaryInterceptor(middleware.UnaryServerInterceptor),
		grpc.StreamInterceptor(middleware.StreamServerInterceptor),
		// Enable TLS for all incoming connections
	}

	grpcServer := grpc.NewServer(opts...)

	api.RegisterHelloServiceServer(grpcServer, NewService())

	listener, err := net.Listen("tcp", ":1234")
	if err != nil {
		panic(err)
	}
	grpcServer.Serve(listener)
}
